import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css' // Progress 进度条样式
import {
  Message
} from 'element-ui'
import {
  getToken, whiteList
} from '@/utils/auth' // 验权
import {
  generaMenu
} from '@/router/tools'

// const whiteList = ['/login', '/downLoadApp', '/contact', '/404', '/401', '/success', '/login/code'] // 不重定向白名单
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (to.meta.title) {
    document.title = to.meta.title
  }
  // 白名单中页面直接进入
  if (whiteList.indexOf(to.path) >= 0) {
    next()
    return
  }
  for (const whitPath of whiteList) {
    if (to.path.indexOf(whitPath) >= 0) {
      next()
      return
    }
  }
  // 未登录
  if (!getToken()) {
    next({
      path: '/login',
      query: {
        redirect: to.fullPath
      }
    })
    NProgress.done()
    return
  }
  // 已登录 拉去用户信息
  const isLogin = store.getters.isLogin
  // const collectAuthPaths = store.getters.collectAuthPaths
  // console.log(collectAuthPaths)
  if (isLogin) {
    next()
    return
  }
  // 重新获取路由
  store.dispatch('GetInfo')
    .then(res => {
      store.dispatch('GetDict')
        .then(res => {
          const asyncRoute = []
          try {
            generaMenu(store.getters.router, asyncRoute)
          } catch (e) {
            console.log(e)
          }
          router.options.routes = asyncRoute
          router.addRoutes(asyncRoute)
          next({ ...to,
            replace: true
          })
        }).catch(err => {
        // 拉去用户信息失败 返回登录页
        console.log('拉取字典信息失败', err)
        store.dispatch('FedLogOut').then(() => {
          Message.error('拉取字典信息失败,请重新登录')
          NProgress.done()
          next({
            path: '/login',
            query: {
              redirect: to.fullPath
            }
          })
        })
      })
    })
    .catch(err => {
      // 拉去用户信息失败 返回登录页
      console.log('登录已过期', err)
      store.dispatch('FedLogOut').then(() => {
        Message.error('验证失败,请重新登录')
        NProgress.done()
        next({
          path: '/login',
          query: {
            redirect: to.fullPath
          }
        })
      })
    })
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})
